package cn.itcast.test.Demo;

import cn.itcast.SearchApp;
import cn.itcast.dao.MerchantDao;
import com.alibaba.fastjson.JSON;

import com.moblie.domain.Merchant;
import org.elasticsearch.action.bulk.BulkRequest;

import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.io.stream.BytesStream;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.GeoDistanceSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import java.util.List;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SearchApp.class)
public class Demo {
    @Autowired
    private MerchantDao merchantDao;
    @Autowired
    private RestHighLevelClient client;
    @Test
    public void test01(){
        System.out.println(merchantDao.findAll());
    }
    /*
    * 数据库中查询数据
    *  存储到
    * */
    @Test
    public  void save() throws IOException {
        List<Merchant> lists = merchantDao.findAll();
//         BulkRequest导入
        BulkRequest bulkRequest=new BulkRequest();
        for(Merchant merchant:lists){
            IndexRequest indexRequest=new IndexRequest("merchant");
            XContentBuilder xContentBuilder= XContentFactory.jsonBuilder()
                    .startObject()
                    .field("id",merchant.getId())
                    .field("score",merchant.getScore())
                    .field("address",merchant.getAddress())
                    .field("price",merchant.getPrice())
                    .field("status",merchant.getStatus())
                    .field("phone",merchant.getPhone())
                    .field("testAvg",merchant.getTasteAvg())
                    .field("environmentAvg",merchant.getEnvironmentAvg())
                    .field("serviceAvg",merchant.getServiceAvg())
                    .field( "foodAvg",merchant.getFoodAvg())
                    .field("totalAvg",merchant.getTotalAvg())
                    .field( "totalEvalute",merchant.getTotalEvaluate())
                    .startObject("location").field("lat",merchant.getLat())
                    .field("lon",merchant.getLon()).endObject();
            /*OutputStream stream = xContentBuilder.getOutputStream();
            indexRequest.source(new BytesArray(((ByteArrayOutputStream) stream).toByteArray()), xContentBuilder.contentType());*/
            indexRequest.source(xContentBuilder);
            //indexRequest.source(xContentBuilder);这个方法是一定会抛异常
            bulkRequest.add(indexRequest);
        }
        BulkResponse response=client.bulk(bulkRequest, RequestOptions.DEFAULT);
        RestStatus status = response.status();
        System.out.println(status);

    }
    @Test
    public void demo04() throws IOException {
        List<Merchant> lists = merchantDao.findAll();
//         BulkRequest导入
        BulkRequest bulkRequest=new BulkRequest();
        for(Merchant merchant:lists){
            double lat = merchant.getLat();
            double lon=merchant.getLon();
            String location=lat+","+lon;
            merchant.setLocation(location);
            String merchantString = JSON.toJSONString(merchant);
            IndexRequest indexRequest=new IndexRequest("merchant");
            indexRequest.id(merchant.getId()+"").source(merchantString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse response=client.bulk(bulkRequest, RequestOptions.DEFAULT);
        RestStatus status = response.status();
        System.out.println(status);
    }
    @Test
    public void query() throws IOException {
//2.创建查询请求对象
        SearchRequest searchRequest = new SearchRequest("merchant");
//4. 创建查询条件构建器SearchSourceBuilder
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//    5.构建查询条件
        //1.构建boolQuery
        BoolQueryBuilder query = QueryBuilders.boolQuery();
//  6.查询构建
        QueryBuilder matchQuery = QueryBuilders.matchQuery("name", "菌汤");
        QueryBuilder matchQuery2 = QueryBuilders.matchQuery("address", "金牛区");
        query.should(matchQuery);
        query.should(matchQuery2);
//  7添加查询条件到构建起中
        sourceBuilder.query(query);
//3. 添加查询条件构建器 SearchSourceBuilder
//        排序规则
        GeoPoint geoPoint = new GeoPoint(30.7088, 104.046653);
        SortBuilder sortBuilder = new GeoDistanceSortBuilder("location", geoPoint);
        sourceBuilder.sort(sortBuilder);
     //设置高亮
        HighlightBuilder highlighter = new HighlightBuilder();
        highlighter.field("name");
        highlighter.field("address");
        highlighter.preTags("<em>");
        highlighter.postTags("</em>");
        sourceBuilder.highlighter(highlighter);




        searchRequest.source(sourceBuilder);
//        查询结果：
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println(search);
        //System.out.println(search);
        SearchHits hits = search.getHits();
        SearchHit[] hits1 = hits.getHits();
        Object sortValue = hits1[1].getSortValues()[0];
        System.out.println(sortValue);



    }



}
